/**
 * Created by kedong on 2017/7/21 0021.
 */
$(function () {
    function getFeatureArray() {
        if (features.getLength == 0) {
            console.log("没有任何要素");
            return [];
        }
        var featureArray = features.getArray();
        var geometrys = featureArray.map(function (e) {
            var geometry = e.getGeometry();
            return geometry;
        });
        return featureArray;
    }

    /**
     * 将要素转换成gpx格式字符串
     * @returns {string}
     */
    function getGPX() {
        var featureArray = getFeatureArray();
        if (featureArray.length == 0) return "";
        var gpxFormat = new ol.format.GPX();
        var gpx = featureArray.map(function (item) {
            if (!item.get('timestamp')) {
                item.set('timestamp', new Date().getTime());
            }
            return '<?xml version="1.0" encoding="GBK"?>' + gpxFormat.writeFeatures([item], {
                    dataProjection: 'EPSG:4326'
                });
        });
        //console.log(gpx);
        return gpx;
    }

    /**
     * 将要素转换成geojson格式字符串
     * @returns {string}
     */
    function getGeoJSON() {
        var featureArray = getFeatureArray();
        if (featureArray.length == 0) return "";
        var geoJsonFormat = new ol.format.GeoJSON();
        var geoJson = featureArray.map(function (item) {
            if (!item.get('timestamp')) {
                item.set('timestamp', new Date().getTime());
            }
            return geoJsonFormat.writeFeatureObject(item, {
                dataProjection: 'EPSG:4326'
            });
        });
        //console.log(geoJson);
        return geoJson;
    }

    /**---------------------------------------订阅信号-----------------------------------------*/
    {
        var first = true;
        /**
         * 保存绘制结果到缓存
         */
        $.subscribe("features:save", function (e) {
            var gpx = getGPX();
            var geoJson = getGeoJSON();

            DB.setArray("gpx", gpx);
            DB.setArray("geoJson", geoJson);

            if (!first) {
                first = true;
                tip();
            }
        });

        /**
         * 从缓存中加载上次绘制的结果
         */
        $.subscribe("features:load", function (e) {
            var geoJson = DB.getArray("geoJson");
            if (!!geoJson && geoJson.length > 0) {
                $.messager.confirm('提示:', '是否继续上次的编辑', function (e) {
                    if (e) {
                        $.publish("features:load_geojson");
                        setTimeout(function () {
                            first = false;
                            $.publish('select:on');
                        }, 1000);
                    } else {
                        DB.removeFeatures();
                    }
                });

            } else {

                // 从服务器加载
                $.get('history', function (data) {
                    if (data.length > 0) {
                        $.messager.confirm('提示:', '是否继续上次的编辑', function (e) {
                            if (e) {
                                var format = new ol.format.GeoJSON();
                                for (var i = data.length - 1; i >= 0; i--) {
                                    var geoJsonFeatures = format.readFeatures(JSON.parse(data[i].geojson)[0]);
                                    addFeatures(geoJsonFeatures);
                                }
                                var zoom = data[0].lastZoom;
                                var center = data[0].lastCenter;
                                var view = map.getView();
                                if (!!zoom) {
                                    view.setZoom(Number(zoom));
                                }
                                if (!!center) {
                                    view.setCenter(JSON.parse(center));
                                }
                            } else {
                                $.publish("history:delete");
                            }
                        })
                    }
                })
            }
        })
        ;

        $.subscribe("history:delete", function (e) {
            $.ajax({
                url: "history",
                type: "delete"
            });
        });

        $.subscribe("features:load_geojson", function (e) {
            var geoJson = DB.getArray("geoJson");
            if (!!geoJson && geoJson.length > 0) {
                try {
                    // geoJson = JSON.parse(geoJson);
                    for (var i = geoJson.length - 1; i >= 0; i--) {
                        var geoJsonFeatures = (new ol.format.GeoJSON()).readFeatures(geoJson[i]);
                        addFeatures(geoJsonFeatures);
                    }
                } catch (e) {
                    console.error('加载GeoJson失败');
                    $.publish("features:load_gpx")
                }
            }
        });

        $.subscribe("features:load_gpx", function (e) {
            var gpx = DB.getArray("gpx");
            if (!!gpx && gpx.length > 0) {
                try {
                    for (var i = gpx.length - 1; i >= 0; i--) {
                        var gpxFeatures = (new ol.format.GPX()).readFeatures(gpx[i]);
                        addFeatures(gpxFeatures);
                    }
                } catch (e) {
                    console.error('加载gpx失败');
                }
            }
        });


        var timer;

        /**
         * 每隔5分钟提示一次
         */
        function tip() {
            clearInterval(timer);
            timer = setInterval(function () {
                $.messager.show({
                    title: '温馨提示:',
                    msg: '本地保存成功!',
                    timeout: 1500,
                    showType: 'slide'
                });
            }, 1000 * 60);
        }
    }

    /**-----------------------------发布信号---------------------------------*/
    {
        // 加载上次编辑未保存的要素
        $.publish("features:load");

    }

    /**
     * 监听窗口关闭事件
     * @param e
     * @returns {string}
     */
    window.onbeforeunload = function (e) {
        return "确定离开";
    };
    window.onunload = function (e) {
        /**
         * 保存操作记录
         */
        if (features.getLength == 0) {
            return;
        }
        var geoJson = DB.getArray("geoJson");

        if (!!geoJson && geoJson.length > 0) {
            var lastZoom = DB.getLastZoom();
            var lastCenter = DB.getLastCenter();

            // 上传本次编辑的状态
            $.post('history', {
                geojson: JSON.stringify(geoJson),
                lastZoom: lastZoom,
                lastCenter: lastCenter
            }, function (res) {
            });
        }
    };

});